<?php

/**
 * Yii Controller SearchController
 *
 * @author trongkhoi
 * @since Oct 7, 2013 - 7:41:39 PM
 */
class SearchController extends FrontController {

    public $layout = '//layouts/browser';
    public $lat = '';
    public $lng = '';
    public $max_price = 0;

    protected function criteria() {

        if (empty($_GET)) {
            $ret = new CDbCriteria();
            $ret->condition = 't.type=:t AND t.book_online>0 AND t.price>0';
            $ret->params = array(
                ':t' => Service::TYPE_SERVICE
            );
            $ret->with = array('category', 'user');
            $ret->compare('category.isshow', Category::SHOW_HOMEPAGE);
            $ret->compare('user.status', Users::STATUS_ACTIVE);
        } else {
            $ret = new CDbCriteria();
            $ret->condition = 't.type=:t AND t.book_online>0 AND t.price>0';
            $ret->params = array(
                ':t' => Service::TYPE_SERVICE
            );

            $ret->with = array('category', 'user');
            $ret->compare('category.isshow', Category::SHOW_HOMEPAGE);

            if (isset($_GET['unavailable_merchant']) && $_GET['unavailable_merchant'] == 1) {
                $ret->compare('user.status', Users::getArrayMerchantStatus());
            } else {
                $ret->compare('user.status', Users::getAvailableStatus());
            }

            /**
             * search by service
             */
            if (isset($_GET['sv_name']) && $_GET['sv_name'] != '') {
                $ret->compare('t.s_name', $_GET['sv_name'], TRUE);
            }

            /**
             * filter by date
             * Tìm toàn bộ những service mà còn giờ trống trong ngày nào đó. 
             * step 1: tìm toàn bộ service, thuộc tính book_online
             * step 2: lấy toàn bộ staff của service
             * step 3: search free time của staff
             * step 4: add remove thông tin staff
             */
            if (isset($_GET['date'])) {
                //tim toan bo service.
                if ($_GET['date'] != '') {

                    //tim toan bo service trong bang tbl_service
                    //neu staff assgin cua staff do
                    //kiem tra staff, neu da full thoi gian thi loai bo service do
                    $list_service = Service::model()->findAll('book_online=:book_online', array(':book_online' => 1));

                    if ($list_service != NULL) {
                        $services_ignore = array();

                        foreach ($list_service as $sv) {
                            //lay toan bo staff duoc assign cho service
                            $list_staff = $sv->staff;


                            if ($list_staff != NULL) {
                                //xét xem có full time không
                                $full_time = false;

                                //duyet tung staff
                                foreach ($list_staff as $staff) {
                                    //neu staff full time
                                    //nếu có một staff full thời gian thì dừng check
                                    if ($this->check_busy_time($staff->id, $sv->totalTime)) {
                                        $full_time = TRUE;
                                    } else {
                                        $full_time = FALSE;
                                        break;
                                    }
                                }
                                if ($full_time) {
                                    $services_ignore[] = $sv->sid;
                                }
                            }
                        }
                        if ($services_ignore != NULL) {
                            $ret->addNotInCondition('t.sid', $services_ignore);
                        }
                    }
                }
            }


            /**
             * search by price
             */
            if (isset($_GET['min_price']) && isset($_GET['max_price'])) {
                $min_price = trim($_GET['min_price'], '$');
                $max_price = trim($_GET['max_price'], '$');

                $ret->addBetweenCondition('t.price', $min_price, $max_price);
            }

            /*
             * filter by cat
             */
            if (isset($_GET['cat'])) {
                if (!is_array($_GET['cat'])) {
                    $ret->compare('t.category_id', $_GET['cat']);
                } else {
                    foreach ($_GET['cat'] as $v) {
                        if ($v > 0) {
                            $ret->addInCondition('t.category_id', $_GET['cat']);
                        }
                    }
                }
            }
            //filter by future date
            if (isset($_GET['future_date']) && $_GET['future_date'] > 0) {
                $crr_date = date('d-m-Y', time());
                $list_future_date = array();
                //array list stamp future date from current date
                for ($i = 1; $i <= $_GET['future_date']; $i++) {
                    $list_future_date[] = strtotime('+' . $i . ' day', strtotime($crr_date));
                }

                //Find All Appoint on Range day
                $cri = new CDbCriteria();
                $cri->condition = 'type=:t';
                $cri->params = array(
                    ':t' => Appoint::TYPE_ROOM
                );
                $cri->addInCondition('date', $list_future_date);
                $appoint = Appoint::model()->findAll($cri);
                $arr_sid = array();
                foreach ($appoint as $v) {
                    $arr_sid[] = $v->service_id;
                }
                array_unique($arr_sid);
                $ret->addInCondition('t.sid', $arr_sid);
            }

            //Filter by area
            if (isset($_GET['area']) && $_GET['area'] != NULL) {
                $cri = new CDbCriteria();
                $cri->addInCondition('area_id', $_GET['area']);
                $area_user = AreaUser::model()->findAll($cri);

                $area_user_arr = array();
                if ($area_user) {
                    foreach ($area_user as $v) {
                        $area_user_arr[] = $v->user_id;
                    }
                }
                $user_arr = array_unique($area_user_arr);
                $ret->addInCondition('t.author_id', $user_arr);
            }
            //Filter by merchant name and merchant category
            if (isset($_GET['merchant_cat']) && $_GET['merchant_cat'] != NULL) {
                //Remove special char
                $arr_keys = explode(',', $_GET['merchant_cat']);

                //Get cat
                $cri = new CDbCriteria();
                foreach ($arr_keys as $key) {
                    $cri->compare('name', trim($key), TRUE, 'OR');
                }
                $biz_cat = BusinessCategory::model()->findAll($cri);
                $arr_cat = array();
                foreach ($biz_cat as $cat) {
                    $arr_cat[] = $cat->id;
                }
                //Get biz cat
                $cri = new CDbCriteria();
                $cri->addInCondition('category_id', $arr_cat);
                $category_user = BusinessCategoryUser::model()->findAll($cri);
                //Get biz id
                $arr_biz_id = array();
                foreach ($category_user as $v) {
                    $arr_biz_id[] = $v->biz_id;
                }
                //Filter merchant name
                $cri = new CDbCriteria();
                foreach ($arr_keys as $key) {
                    $cri->compare('business_name', $key, TRUE, 'OR');
                }
                $merchants = Users::model()->findAll($cri);
                $biz_filter_name = array();
                foreach ($merchants as $merchant) {
                    $biz_filter_name[] = $merchant->id;
                }
                $user_arr = array_merge($arr_biz_id, $biz_filter_name); //Gộp 2 mảng
                $user_arr_unique = array_unique($user_arr);
                $ret->addInCondition('t.author_id', $user_arr_unique);
            }
        }
        return $ret;
    }

    private function MerchantCriteria() {
        $merchant_name = isset($_GET['m']) ? $_GET['m'] : '';

        $ret = new CDbCriteria();

        $ret->select = array('id', 'type', 'postal_code', 'business_name', 'address', 'business_description');
        $ret->compare('type', Users::TYPE_BUSINESS);
        if ($merchant_name != NULL OR $merchant_name != '') {
            $ret->compare('business_name', $merchant_name, TRUE, 'AND');
        }

        //Filter only active merchant
        if (isset($_GET['available_merchant']) && $_GET['available_merchant'] == 1) {
            $ret->compare('status', Users::STATUS_ACTIVE);
        }

        //Filter by area
        if (isset($_GET['area']) && $_GET['area'] != NULL) {
            $cri = new CDbCriteria();
            $cri->addInCondition('area_id', $_GET['area']);
            $area_user = AreaUser::model()->findAll($cri);

            $area_user_arr = array();
            if ($area_user) {
                foreach ($area_user as $v) {
                    $area_user_arr[] = $v->user_id;
                }
            }
            $user_arr = array_unique($area_user_arr);
            $ret->addInCondition('id', $user_arr);
        }
        //Filter by merchant name and merchant category
        if (isset($_GET['merchant_cat']) && $_GET['merchant_cat'] != NULL) {
            //Remove special char
            $arr_keys = explode(',', $_GET['merchant_cat']);

            //Get cat
            $crite = new CDbCriteria();
            foreach ($arr_keys as $key) {
                $crite->compare('name', trim($key), TRUE, 'OR');
            }
            $biz_cat = BusinessCategory::model()->findAll($crite);
            $arr_cat = array();
            foreach ($biz_cat as $cat) {
                $arr_cat[] = $cat->id;
            }
            //Get biz cat
            $cri = new CDbCriteria();
            $cri->addInCondition('category_id', $arr_cat);
            $category_user = BusinessCategoryUser::model()->findAll($cri);
            //Get biz id
            $arr_biz_id = array();
            foreach ($category_user as $v) {
                $arr_biz_id[] = $v->biz_id;
            }

            $ret->addInCondition('id', $arr_biz_id);
        }

        return $ret;
    }

    /**
     * only for searching merchant
     */
    public function actionMerchant() {
        //$crite = $this->MerchantCriteria();
        //$crite->limit = 8;
        //$crite->offset = 0;
        //Yii::app()->session['offset_merchant'] = 0;
        //$model = Users::model()->findAll($crite);

        $this->render('searchmerchant', array(
                //'model' => $model
        ));
    }

    public function actionAjaxListMerchant() {
        $crite = $this->MerchantCriteria();
        $offset = Yii::app()->session['offset_merchant'] + 8;
        Yii::app()->session['offset_merchant'] = $offset;

        $crite->limit = 8;
        $crite->offset = $offset;

        //if lazdy load
//            if ($_GET['is_lazdy'] == 'lazdy' && $model == NULL)
//            {
//                echo 'ok';
//                Yii::app()->end();
//            }



        $model = Users::model()->findAll($crite);
        echo $this->renderPartial('_list_merchant', array(
            'model' => $model
        ));
        Yii::app()->end();
    }

    /**
     * get a CDB CDbcriteri
     * @return \CDbCriteria 
     */
    protected function RoomCriteria() {
        $ret = new CDbCriteria();
        $ret->with = array('service');
        $ret->condition = 't.type=:t AND t.date>:d AND t.slot=:slot AND service.book_online>0 AND service.price>0';
        $ret->params = array(
            ':t' => Appoint::TYPE_ROOM,
            ':slot' => Room::AVAIABLE_SLOT,
            /**
             * @VOITHAN
             */
            //giả sử date xảy ra trong ngày hôm nay thì date luôn luôn nhỏ hơn time()
            ':d' => Utils::getResetTimeStamp(time())
        );

        /**
         * Search by approximate price
         */
        if (isset($_GET['min_price']) && isset($_GET['max_price'])) {
            $min_price = trim($_GET['min_price'], '$');
            $max_price = trim($_GET['max_price'], '$');
            $ret->with = array('service');
            $ret->addBetweenCondition('service.price', $min_price, $max_price);
        }

        /**
         * search by service
         */
        $ret->with = array('service');
        if (isset($_GET['sv_name']) && $_GET['sv_name'] != '') {
            $ret->compare('service.s_name', $_GET['sv_name'], TRUE);
        }

        /*
         * Filter by cat
         */
        if (isset($_GET['cat'])) {
            foreach ($_GET['cat'] as $v) {
                if ($v > 0) {
                    $ret->with = array('service');
                    $ret->addInCondition('service.category_id', $_GET['cat']);
                }
            }
        }
        //filter by future date
        if (isset($_GET['future_date']) && $_GET['future_date'] > 0) {
            $crr_date = date('d-m-Y', time());
            $list_future_date = array();
            //array list stamp future date from current date
            for ($i = 1; $i <= $_GET['future_date']; $i++) {
                $list_future_date[] = strtotime('+' . $i . ' day', strtotime($crr_date));
            }

            //Find All Appoint on Range day

            $ret->addInCondition('date', $list_future_date);
        }

        //Filter by area
        if (isset($_GET['area']) && $_GET['area'] != NULL) {
            $cri = new CDbCriteria();
            $cri->addInCondition('area_id', $_GET['area']);
            $area_user = AreaUser::model()->findAll($cri);

            $area_user_arr = array();
            if ($area_user) {
                foreach ($area_user as $v) {
                    $area_user_arr[] = $v->user_id;
                }
            }
            $user_arr = array_unique($area_user_arr);
            $ret->addInCondition('service.author_id', $user_arr);
        }
        //Filter by merchant category
        if (isset($_GET['merchant_cat']) && $_GET['merchant_cat'] != NULL) {
            //Remove special char and "and"
            $arr_keys = explode(',', $_GET['merchant_cat']);

            //Get cat
            $cri = new CDbCriteria();
            foreach ($arr_keys as $key) {
                $cri->compare('name', trim($key), TRUE, 'OR');
            }
            $biz_cat = BusinessCategory::model()->findAll($cri);
            $arr_cat = array();
            foreach ($biz_cat as $cat) {
                $arr_cat[] = $cat->id;
            }
            //Get biz cat
            $cri = new CDbCriteria();
            $cri->addInCondition('category_id', $arr_cat);
            $category_user = BusinessCategoryUser::model()->findAll($cri);
            //Get biz id
            $arr_biz_id = array();
            foreach ($category_user as $v) {
                $arr_biz_id[] = $v->biz_id;
            }

            //Filter by merchant name
            $cri = new CDbCriteria();
            foreach ($arr_keys as $key) {
                $cri->compare('business_name', $key, TRUE, 'OR');
            }
            $merchants = Users::model()->findAll($cri);
            $biz_filter_name = array();
            foreach ($merchants as $merchant) {
                $biz_filter_name[] = $merchant->id;
            }
            $user_arr = array_merge($arr_biz_id, $biz_filter_name);
            //Remove dup
            $user_arr_unique = array_unique($user_arr);
            $ret->addInCondition('service.author_id', $user_arr_unique);
        }
        //filter by Merchant status is active
        $ret->with = array('service', 'service.user');
        if (isset($_GET['unavailable_merchant']) && $_GET['unavailable_merchant'] == 1) {
            $ret->compare('user.status', Users::getArrayMerchantStatus());
        } else {
            $ret->compare('user.status', Users::getAvailableStatus());
        }

        return $ret;
    }

    /**
     * Check thời gian trông của một staff vào một ngày nhất định.
     * @param string $date
     * @param int $sid
     * @param type $hour_start
     * @param type $minute_start
     * @param type $hour_end
     * @param type $minute_end
     * @return boolean <b>TRUE</b> if staff is busy and <b>FLASE</b> if otherwise
     */
    private function check_busy_time($sid, $time_service) {
        if (isset($_GET['start']) & $_GET['start'] != '') {
            $start = $_GET['start'];
        } else {
            $start = '00:00';
        }

        if (isset($_GET['end']) & $_GET['end'] != '') {
            $end = $_GET['end'];
        } else {
            $end = '23:59';
        }

        $date = strtotime($_GET['date']);

        $list_appoint = Appoint::model()->findAll('date=:date', array(':date' => $date));

        if ($list_appoint == NULL) {
            return FALSE;
        } else {
            foreach ($list_appoint as $apt) {
                //true : ban
                //false: khong ban
                if (!$this->check_time($start, $end, $apt->start_time, $apt->end_time, $time_service)) {
                    return FALSE;
                    break;
                }
            }
            return TRUE;
        }
    }

    /**
     * 
     * @param type $start
     * @param type $end
     * @param type $apt_start
     * @param type $apt_end
     * @param type $time_service
     * @return boolean <b>TRUE</b> nếu bận or <b>FALSE</b> nếu không bận
     */
    public function check_time($start, $end, $apt_start, $apt_end, $time_service) {

        //neu thời gian bắt đầu+thời gian service(duration+recover) < thời gian 
        //bắt đầu của service trong calendar 
        if ((strtotime($start) + Utils::minutesToTimeStamp($time_service)) > strtotime($apt_start)) {
            return TRUE;
        }

        if ((strtotime($end) < (strtotime($apt_end) + Utils::minutesToTimeStamp($time_service)))) {
            return TRUE;
        }

        return FALSE;
    }

    public function actionAjaxListStyle() {

        if (Yii::app()->session['out_of_merchant'] == 'true' AND $_GET['style'] == 'gallery') {
            echo 'ok';
            Yii::app()->end();
        }

        if (Yii::app()->session['out_of_merchant_list'] == 'true' AND $_GET['style'] == 'list') {
            echo 'ok';
            Yii::app()->end();
        }

        $crite = $this->criteria();
        $list_service = Service::model()->findAll($crite);

        $crr_id = Yii::app()->session['offset_merchant'];
        $crr_id_list = Yii::app()->session['offset_merchant_list'];
        $continua = TRUE;
        $result = array();

        if ($_GET['type'] == 'service') {
            if (TRUE) { {
                    if ($_GET['style'] == 'gallery') {

                        /**
                         * Moi lan tra ve 6 merchant, neu nho hon + chua duyet het 
                         * cac merchant thi tiep tuc tim kiem
                         */
                        while (sizeof($result) < 6 AND $continua) {
                            //tim merchant tiep theo
                            $merchant = Yii::app()->user->getNextOrPrevId($crr_id, 'next');

                            //neu tim thay merchant
                            if ($merchant) {
                                if ($merchant->id == Users::model()->getLastMerchant()->id) {

                                    $continua = FALSE;
                                    Yii::app()->session['out_of_merchant'] = 'true';
                                }
                                foreach ($list_service as $service) {
                                    if ($service->author_id == $merchant->id) {
                                        $result[$merchant->id][] = $service;
                                    }
                                }
                                $crr_id++;
                            } else {

                                $crr_id++;
                            }
                        }
                        Yii::app()->session['offset_merchant'] = $crr_id;
                    } else {
                        /**
                         * Moi lan tra ve 6 merchant, neu nho hon + chua duyet het 
                         * cac merchant thi tiep tuc tim kiem
                         */
                        while (sizeof($result) < 6 AND $continua) {
                            //tim merchant tiep theo
                            $merchant = Yii::app()->user->getNextOrPrevId($crr_id_list, 'next');

                            //neu tim thay merchant
                            if ($merchant) {
                                if ($merchant->id == Users::model()->getLastMerchant()->id) {

                                    $continua = FALSE;
                                    Yii::app()->session['out_of_merchant_list'] = 'true';
                                }
                                foreach ($list_service as $service) {
                                    if ($service->author_id == $merchant->id) {
                                        $result[$merchant->id][] = $service;
                                    }
                                }
                                $crr_id_list++;
                            } else {

                                $crr_id_list++;
                            }
                        }
                        Yii::app()->session['offset_merchant_list'] = $crr_id_list;
                    }
                }
            }


            //if lazdy load
            if ($_GET['is_lazdy'] == 'lazdy' && $result == NULL) {
                echo 'ok';
                Yii::app()->end();
            }

            if ($_GET['style'] == 'gallery') {
                echo $this->renderPartial('_gallery', array(
                    'merchant_list' => $result
                ));
                Yii::app()->end();
            } else {
                echo $this->renderPartial('_list', array(
                    'merchant_list' => $result
                ));
                Yii::app()->end();
            }
        } else {
            //room
            $ret = $this->RoomCriteria();

            if ($ret) {

                if ($_GET['is_lazdy'] == 'loadnew') {
                    $ret->limit = 8;
                    $ret->offset = 0;

                    if ($_GET['style'] == 'gallery') {
                        Yii::app()->session['offset_gallery'] = 0;
                    } else {
                        Yii::app()->session['offset_list'] = 0;
                    }
                } else {
                    $offset = 0;
                    if ($_GET['style'] == 'gallery') {
                        $offset = Yii::app()->session['offset_gallery'] + 8;
                        Yii::app()->session['offset_gallery'] = $offset;
                    } else {
                        $offset = Yii::app()->session['offset_list'] + 8;
                        Yii::app()->session['offset_list'] = $offset;
                    }

                    $ret->limit = 8;
                    $ret->offset = $offset;
                }

                $model = Appoint::model()->findAll($ret);
            } else {
                $model = NULL;
            }

            //if lazdy load
            if ($_GET['is_lazdy'] == 'lazdy' && $model == NULL) {
                echo 'ok';
                Yii::app()->end();
            }


            if ($_GET['style'] == 'gallery') {

                echo $this->renderPartial('/room/_gallery', array(
                    'model' => $model
                ));
                Yii::app()->end();
            } else {
                echo $this->renderPartial('/room/_list', array(
                    'model' => $model,
                ));
                Yii::app()->end();
            }
        }
    }

    public function actionIndex() {

        Yii::app()->session['out_of_merchant'] = 'false';
        Yii::app()->session['out_of_merchant_list'] = 'false';

        Yii::app()->session['offset_merchant_list'] = 1;
        Yii::app()->session['offset_merchant'] = 1;

        $crr_id = 1;
        $continua = TRUE;
        //lay thang merchant dau tien
        //neu no co service thoai man thi cho vao array
        //neu khong thoa =>  next 
//        $crite = $this->criteria();
//        $list_service = Service::model()->findAll($crite);


        $result = array();


//        while (sizeof($result) < 7 AND $continua)
//        {
//
//            $merchant = Users::model()->findByPk($crr_id,'type=:type AND status=:status',array(
//                ':type'=>  Users::TYPE_BUSINESS,':status'=>  Users::STATUS_ACTIVE));
//
//
//            if ($merchant)
//            {
//                if ($merchant->id == Users::model()->getLastMerchant()->id)
//                {
//
//                    $continua = FALSE;
//                    Yii::app()->session['out_of_merchant']='true';
//                    Yii::app()->session['out_of_merchant_list']='false';
//                }
//                foreach ($list_service as $service)
//                {
//                    if ($service->author_id == $merchant->id)
//                    {
//                        $result[$merchant->id][] = $service;
//                    }
//                }
//
//                $crr_id++;
//            }
//            else
//            {
//                $crr_id++;
//            }
//        }

        Yii::app()->session['offset_merchant'] = $crr_id;
        Yii::app()->session['offset_merchant_list'] = $crr_id;

        $this->render('index', array(
            'merchant_list' => $result
        ));
    }

    public function getArrPostalCode($model) {
        $ukey = Users::getUkeyById(Yii::app()->user->getId());
//        sid, name, img, price, urlbooking, address, bizname, detailurl, icon_class, rate, vote_time, icon_title
        $array = array();
        foreach ($model as $val) {
            $icon_class = (!Yii::app()->user->isGuest && Favourite::checkAdded($ukey, $val->sid)) ? '<i class="icon-heart-pink"></i>' : '<i class="icon-heart-white"></i>';
            $icon_title = Favourite::checkAdded($ukey, $val->sid) ? 'Remove from My Favourites' : 'Add to Favourites';
            $avr_point = ServiceRate::getAvrPoint($val->sid);
            $rate = $this->genArrayVote($avr_point, 5, $val->sid);
            $vote_time = ServiceRate::getReviewTimes($val->sid);
            $array[] = array(
                'postalcode' => $val->postal_code ? "[Singapore #$val->postal_code]" : '',
                'sname' => $val->s_name,
                'avatar' => $val->publicAvatar,
                'sid' => $val->sid,
                'price' => $val->price,
                'urlbooking' => $val->bookingUrl,
                'address' => $val->address,
                'bizname' => $val->user->business_name,
                'detailurl' => $val->detailurl,
                'icon_class' => $icon_class,
                'rate' => $rate,
                'vote_time' => $vote_time,
                'icon_title' => $icon_title
            );
        }
        return json_encode($array);
    }

    public function actionGallery() {
        $offset = Yii::app()->session['offset_gallery'] + $this->currentLimit;
        $crite = $this->criteria();
        $crite->limit = $this->currentLimit;
        $crite->offset = $offset;

        Yii::app()->session['offset_gallery'] = $offset;

        $model = Service::model()->findAll($crite);
        if ($model != NULL) {
            echo $this->renderPartial('/favourite/_gallery', array('model' => $model));
            Yii::app()->end();
        } else {
            echo 'ok';
            Yii::app()->end();
        }
    }

    public function actionList() {
        $offset = Yii::app()->session['offset_list'] + $this->currentLimit;
        $crite = $this->criteria();
        $crite->limit = $this->currentLimit;
        $crite->offset = $offset;

        Yii::app()->session['offset_list'] = $offset;

        $model = Service::model()->findAll($crite);
        if ($model != NULL) {
            echo $this->renderPartial('/favourite/_list', array('model' => $model));
            Yii::app()->end();
        } else {
            echo 'ok';
            Yii::app()->end();
        }
    }

    public function actionGetAllService() {
        $service = Service::model()->findAll($this->criteria());
        $result_arr = array();

        $ukey = Users::getUkeyById(Yii::app()->user->getId());
        foreach ($service as $sv) {
            if ($sv->longitude != '') {
                $icon_class = (!Yii::app()->user->isGuest && Favourite::checkAdded($ukey, $sv->sid)) ? '<i class="icon-heart-pink"></i>' : '<i class="icon-heart-white"></i>';
                $icon_title = Favourite::checkAdded($ukey, $sv->sid) ? Yii::t('frontend','Remove from My Favourites') : Yii::t('frontend','Add to Favourites');
                $avr_point = ServiceRate::getAvrPoint($sv->sid);
                $rate = $this->genArrayVote($avr_point, 5, $sv->sid);
                $vote_time = ServiceRate::getReviewTimes($sv->sid);
                $result_arr[] = array(
                    'sid' => $sv->sid,
                    'lng' => $sv->longitude,
                    'lat' => $sv->latitude,
                    'name' => $sv->s_name,
                    'price' => $sv->price,
                    'avatar' => $sv->publicAvatar,
                    'bookingurl' => $sv->bookingUrl,
                    'detailurl' => $sv->detailUrl,
                    'address' => $sv->address,
                    'bizname' => $sv->user->business_name,
                    'icon_class' => $icon_class,
                    'rate' => $rate,
                    'vote_time' => $vote_time,
                    'icon_title' => $icon_title
                );
            }
        }

        echo json_encode($result_arr);
        Yii::app()->end();
    }

    private function genArrayVote($point, $total, $sid) {
        $arr = array();
        $count_time = 0;
        while ($point >= 1 && $count_time <= $total) {
            $arr[] = 'full';
            $point-=1;
            $count_time+=1;
        }

        if ($point > 0) {
            $arr[] = 'half';
            $count_time+=1;
        }

        while ($count_time < 5) {
            $arr[] = 'blank';
            $count_time+=1;
        }
        return $arr;
    }

    public function actionAjaxVote() {
        if (!ServiceRate::checkRated($_GET['sid'], Yii::app()->user->getId())) {

            $sv_rate = new ServiceRate();
            $sv_rate->user_id = Yii::app()->user->getId();
            $sv_rate->sid = $_GET['sid'];
            $sv_rate->points = $_GET['point'];
        } else {
            $sv_rate = ServiceRate::model()->find('sid=:sid AND user_id=:uid', array(
                ':sid' => $_GET['sid'],
                ':uid' => Yii::app()->user->getId()
            ));
            $sv_rate->points = $_GET['point'];
        }
        if ($sv_rate->save()) {
            $avr_point = ServiceRate::getAvrPoint($_GET['sid']);
            echo Utils::getContentVote($avr_point, 5, $_GET['sid']);
        }
    }

    public function actionAjaxGetCateByGroup() {
        $result = array();
        //Filter by merchant name and merchant category
        if (isset($_GET['merchant_cat']) && $_GET['merchant_cat'] != NULL && $_GET['merchant_cat'] != '') {
            //Remove special char
            $arr_keys = explode(',', $_GET['merchant_cat']);
            //Get cat
            $cri = new CDbCriteria();
            foreach ($arr_keys as $key) {
                if ($key != '' && $key != NULL) {
                    $cri->compare('name', trim($key), TRUE, 'OR');
                }
            }
            $group_cate = BusinessCategory::model()->findAll($cri);

            foreach ($group_cate as $v) {
                foreach ($v->categories as $cate) {
                    $result[] = array(
                        'id' => $cate->category_id,
                        'name' => $cate->name
                    );
                }
            }
        } else {
            $cate = Category::GetAllCat(FALSE);
            foreach ($cate as $id => $name) {
                $result[] = array(
                    'id' => $id,
                    'name' => $name
                );
            }
        }
        echo json_encode($result);
        Yii::app()->end();
    }

    //Get Data for browser page
    public function actionGetData() {
        if (isset($_POST['load_merchat_item']) && $_POST['load_merchat_item'] == 'yes') {
            $list_merchant = BusinessCategory::model()->getData();
        }
        echo json_encode($list_merchant);
        Yii::app()->end();
    }

    //Get data for search merchant page
    public function actionGetMerchantList() {
        if (isset($_POST['load_merchat_list']) && $_POST['load_merchat_list'] == 'yes') {
            $list_merchant = BusinessCategory::model()->getMerchantList();
        }
        echo json_encode($list_merchant);
        Yii::app()->end();
    }

}

/** 
* End file SearchController
*/
